package jwlee.testfile;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

/**
 * �����ļ�
 */
public class FileHelper {
	public FileHelper() {
	}

	/**
	 * ɾ��ĳ���ļ����µ������ļ��к��ļ�
	 */
	public static void deleteFile(String filepath) {
		File file = new File(filepath);
		if(!file.exists()){
			System.out.println("�ļ�������!");
			return;
		}
		if (!file.isDirectory()) {
			System.out.println("�ļ�");
			file.delete();
		} else {
			System.out.println("�ļ���");
			String[] fileNameList = file.list();
			for (int i = 0; i < fileNameList.length; i++) {
				File perFile = new File(filepath + "\\" + fileNameList[i]);
				if (!perFile.isDirectory()) {
					System.out.println("path=" + perFile.getPath());
					System.out.println("absolutepath="
							+ perFile.getAbsolutePath());
					System.out.println("name=" + perFile.getName());
					perFile.delete();
					System.out.println("ɾ���ļ��ɹ�");
				} else {
					deleteFile(filepath + "\\" + fileNameList[i]);
				}
			}
			file.delete();
		}
	}

	/**
	 * ��ȡĳ���ļ����µ������ļ��к��ļ�
	 */
	public static void readFile(String filepath) {
		File file = new File(filepath);
		if (!file.isDirectory()) {
			System.out.println("�ļ�");
			System.out.println("path=" + file.getPath());
			System.out.println("absolutepath=" + file.getAbsolutePath());
			System.out.println("name=" + file.getName());
		} else {
			System.out.println("�ļ���");
			String[] fileNameList = file.list();
			File perFile;
			for (int i = 0; i < fileNameList.length; i++) {
				perFile = new File(filepath + "\\" + fileNameList[i]);
				if (!perFile.isDirectory()) {
					System.out.println("path=" + perFile.getPath());
					System.out.println("absolutepath="
							+ perFile.getAbsolutePath());
					System.out.println("name=" + perFile.getName());
				} else {
					readFile(filepath + "\\" + fileNameList[i]);
				}
			}
		}
	}
	
	/**
	 * ���ش�Ŀ¼�µ��ļ��б�
	 * @param directorypath
	 * @return
	 */
	public static List getFileList(File directory) {
		if (!directory.isDirectory()) {
			return null;
		}
		String[] fileNames = directory.list();
		List fileList = new ArrayList();
		File perFile;
		for (int i = 0; i < fileNames.length; i++) {
			perFile = new File(directory.getPath() + "\\" + fileNames[i]);
			fileList.add(perFile);
		}
		return fileList;
	}
	
	public static String[] getFileNames(String dirPath) {
		File directory = new File(dirPath);
		if (!directory.isDirectory()) {
			return null;
		}
		String[] fileNames = directory.list();
		return fileNames;
	}

	/**
	 * ���ļ�����
	 */
	private static void changeFileNames() {
		File dir = new File("E:/����˲�2");
		List fileList = getFileList(dir);
		File f;
		for (int i = 0; i < fileList.size(); i++) {
			f = (File) fileList.get(i);
			
			//����Ĵ�����
			String oldname = f.getName();
			System.out.println("oldname:" + oldname);
			String[] names = oldname.split("��");
			if (names.length != 2) {
				continue;
			}
			String newname = names[1];
			System.out.println("newname:" + newname);
			
			f.renameTo(new File(dir.getAbsolutePath() + "\\" + newname));
		}
	}
	
	/**
	* �õ��ļ���)չ��
	* @param fileName
	* @return
	*/
	public static String getExtention(String fileName) {
		int pos = fileName.lastIndexOf(".");
		return fileName.substring(pos + 1);
	}
	/**
	 * �õ��ļ���)չ��
	 * @param file
	 * @return
	 */
	public static String getExtention(File file) {
		int pos = file.getName().lastIndexOf(".");
		return file.getName().substring(pos + 1);
	}
	
	/**
     * ��ȡ�ı��ļ�����
     * @param filePathAndName ����������·�����ļ���
     * @param encoding �ı��ļ��򿪵ı��뷽ʽ
     * @return �����ı��ļ�������
     */
    public static String readTxt(String filePathAndName, String encoding)
			throws IOException {
		encoding = encoding.trim();
		StringBuffer str = new StringBuffer("");
		String st = "";
		try {
			FileInputStream fs = new FileInputStream(filePathAndName);
			InputStreamReader isr;
			if (encoding.equals("")) {
				isr = new InputStreamReader(fs);
			} else {
				isr = new InputStreamReader(fs, encoding);
			}
			BufferedReader br = new BufferedReader(isr);
			try {
				String data = "";
				while ((data = br.readLine()) != null) {
					str.append(data + " ");
				}
			} catch (Exception e) {
				str.append(e.toString());
			}
			st = str.toString();
		} catch (IOException es) {
			st = "";
		}
		return st;
	}

    /**
	 * �½�Ŀ¼
	 * 
	 * @param folderPath
	 *            Ŀ¼
	 * @return ����Ŀ¼�������·��
	 */
    public static String createFolder(String folderPath) {
		String txt = folderPath;
		java.io.File myFilePath = new java.io.File(txt);
		txt = folderPath;
		if (!myFilePath.exists()) {
			myFilePath.mkdir();
		}
		return txt;
	}
    
    /**
	 * �༶Ŀ¼����
	 * 
	 * @param folderPath
	 *            ׼��Ҫ�ڱ���Ŀ¼�´�����Ŀ¼��Ŀ¼·�� ���� c:myf
	 * @param paths
	 *            ���޼�Ŀ¼�����Ŀ¼�Ե�������� ���� a|b|c
	 * @return ���ش����ļ����·�� ���� c:myfac
	 */
    public static String createFolders(String folderPath, String paths) {
		String txts = folderPath;
		String txt;
		txts = folderPath;
		StringTokenizer st = new StringTokenizer(paths, "|");
		for (int i = 0; st.hasMoreTokens(); i++) {
			txt = st.nextToken().trim();
			if (txts.lastIndexOf("/") != -1) {
				txts = createFolder(txts + txt);
			} else {
				txts = createFolder(txts + txt + "/");
			}
		}
		return txts;
	}

    
    /**
	 * �½��ļ�
	 * 
	 * @param filePathAndName
	 *            �ı��ļ�������·�����ļ���
	 * @param fileContent
	 *            �ı��ļ�����
	 * @return
     * @throws IOException 
	 */
    public static void createFile(String filePathAndName, String fileContent) throws IOException {
		String filePath = filePathAndName;
		filePath = filePath.toString();
		File myFilePath = new File(filePath);
		if (!myFilePath.exists()) {
			myFilePath.createNewFile();
		}
		FileWriter resultFile = new FileWriter(myFilePath);
		PrintWriter myFile = new PrintWriter(resultFile);
		String strContent = fileContent;
		myFile.println(strContent);
		myFile.close();
		resultFile.close();
	}


    /**
	 * �б��뷽ʽ���ļ�����
	 * 
	 * @param filePathAndName
	 *            �ı��ļ�������·�����ļ���
	 * @param fileContent
	 *            �ı��ļ�����
	 * @param encoding
	 *            ���뷽ʽ ���� GBK ���� UTF-8
	 * @return
     * @throws IOException 
	 */
    public static void createFile(String filePathAndName, String fileContent,
			String encoding) throws IOException {
		File myFilePath = new File(filePathAndName);
		if (!myFilePath.exists()) {
			myFilePath.createNewFile();
		}
		// FileWriter resultFile = new FileWriter(myFilePath);
		// OutputStreamWriter myFile = new OutputStreamWriter
		// (resultFile,encoding);
		FileOutputStream fos = new FileOutputStream(myFilePath);
		OutputStreamWriter writer = new OutputStreamWriter(fos, encoding);
		writer.write(fileContent);

		// writer.println(fileContent);
		writer.close();
	} 


    /**
	 * ɾ���ļ�
	 * 
	 * @param filePathAndName
	 *            �ı��ļ�������·�����ļ���
	 * @return Boolean �ɹ�ɾ���true�����쳣����false
	 */
    public static boolean delFile(String filePathAndName) {
		boolean bea = false;
		String filePath = filePathAndName;
		File myDelFile = new File(filePath);
		if (myDelFile.exists()) {
			myDelFile.delete();
			bea = true;
		} else {
			bea = false;
		}
		return bea;
	}
    


    /**
	 * ɾ���ļ���
	 * 
	 * @param folderPath
	 *            �ļ���������·��
	 * @return
	 */
    public static void delFolder(String folderPath) {
		delAllFile(folderPath); // ɾ����������������
		String filePath = folderPath;
		filePath = filePath.toString();
		java.io.File myFilePath = new java.io.File(filePath);
		myFilePath.delete(); // ɾ����ļ���
	}
    
    
    /**
	 * ɾ��ָ���ļ����������ļ�
	 * 
	 * @param path
	 *            �ļ���������·��
	 * @return
	 * @return
	 */
    public static boolean delAllFile(String path) {
		boolean bea = false;
		File file = new File(path);
		if (!file.exists()) {
			return false;
		}
		if (!file.isDirectory()) {
			return false;
		}
		String[] tempList = file.list();
		File temp = null;
		for (int i = 0; i < tempList.length; i++) {
			if (path.endsWith(File.separator)) {
				temp = new File(path + tempList[i]);
			} else {
				temp = new File(path + File.separator + tempList[i]);
			}
			if (temp.isFile()) {
				temp.delete();
			}
			if (temp.isDirectory()) {
				delAllFile(path + "/" + tempList[i]);// ��ɾ���ļ���������ļ�
				delFolder(path + "/" + tempList[i]);// ��ɾ����ļ���
				bea = true;
			}
		}
		return bea;
	}


    /**
	 * ���Ƶ����ļ�
	 * 
	 * @param oldPathFile
	 *            ׼�����Ƶ��ļ�Դ
	 * @param newPathFile
	 *            �������¾��·�����ļ���
	 * @return
	 * @throws IOException
	 */
    public static void copyFile(String oldPathFile, String newPathFile) throws IOException {
		int bytesum = 0;
		int byteread = 0;
		File oldfile = new File(oldPathFile);
		if (oldfile.exists()) { // �ļ�����ʱ
			InputStream fis = new FileInputStream(oldPathFile); // ����ԭ�ļ�
			OutputStream fos = new FileOutputStream(newPathFile);
			byte[] buffer = new byte[1444];
			while ((byteread = fis.read(buffer)) != -1) {
				bytesum += byteread; // �ֽ��� �ļ���С
				System.out.println(bytesum);
				fos.write(buffer, 0, byteread);
			}
			fis.close();
		}
	}
    

    /**
	 * ��������ļ��е�����
	 * 
	 * @param oldPath
	 *            ׼��������Ŀ¼
	 * @param newPath
	 *            ָ�����·������Ŀ¼
	 * @return
     * @throws IOException 
	 */
    public static void copyFolder(String oldPath, String newPath) throws IOException {
            new File(newPath).mkdirs(); //����ļ��в����� ��b���ļ���
            File a=new File(oldPath);
            String[] file=a.list();
            File temp=null;
            for (int i = 0; i < file.length; i++) {
                if(oldPath.endsWith(File.separator)){
                    temp=new File(oldPath+file[i]);
                }else{
                    temp=new File(oldPath+File.separator+file[i]);
                }
                if(temp.isFile()){
                    FileInputStream input = new FileInputStream(temp);
                    FileOutputStream output = new FileOutputStream(newPath + "/" +
                    (temp.getName()).toString());
                    byte[] b = new byte[1024 * 5];
                    int len;
                    while ((len = input.read(b)) != -1) {
                        output.write(b, 0, len);
                    }
                    output.flush();
                    output.close();
                    input.close();
                }
                if(temp.isDirectory()){//��������ļ���
                    copyFolder(oldPath+"/"+file[i],newPath+"/"+file[i]);
                }
            }
    }


    /**
     * �ƶ��ļ�
     * @param oldPath
     * @param newPath
     * @return
     * @throws IOException 
     */
    public static void moveFile(String oldPath, String newPath) throws IOException {
        copyFile(oldPath, newPath);
        delFile(oldPath);
    }
    

    /**
     * �ƶ�Ŀ¼
     * @param oldPath
     * @param newPath
     * @return
     * @throws IOException 
     */
    public static void moveFolder(String oldPath, String newPath) throws IOException {
        copyFolder(oldPath, newPath);
        delFolder(oldPath);
    }
	
	public static void main(String[] args) throws Exception {
		//readFile("E:/����˲�");
		// deletefile("D:/file");
		//changeFileNames();
		//System.out.println(getExtention(new File("e:\\��ӹȫ��1.exe")));
//		createFile("e:\\1.txt","hello","utf-8");
		String[] filenames = getFileNames("D:\\Oracle\\Middleware\\user_projects\\domains\\adp\\frameLib");
		for (String filename : filenames) {
			int pos = filename.lastIndexOf(".");
			if ("jar".equals(filename.substring(pos + 1)))
				System.out
						.println("set FRAME_CLASSES=%FRAME_CLASSES%;"
								+ filename);
		}
	}
}